module(..., package.seeall)

local widget = require "widget"

local imgPath = "images/"

local myImages = {}
local myCoins  = {}
local myImages2 = {
	"jessica_100.jpg",
	"andy_100.jpg",
	"aya_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg",
	"jessica_100.jpg"
}
local sql = "SELECT cb.*,m.img_320,m.mon_name,m._id as m_id from coinbox cb" ..
			" LEFT JOIN monster m ON cb.monster_id=m._id"
--for row in db:nrows("SELECT * FROM monster_slot") do
for row in db:nrows(sql) do
	table.insert(myImages,imgPath .. row.img_320)
	table.insert(myCoins,row.m_id)
end
print(myImages[0])


local index = 1
local CURR_MONSTER_ID = preference.getValue("CURR_MONSTER_ID")
local CURR_SLOT_NO = preference.getValue("CURR_SLOT_NO")
if (CURR_SLOT_NO == nil) then
	CURR_SLOT_NO = 1
	index = 1
else
	index = CURR_SLOT_NO -- must change to getIndexFromMonsterId()!
end
--====================================================================--
-- SCENE: LAB
--====================================================================--

new = function ( params )
	
	------------------
	-- Params
	------------------
	
	local vLabel = "- LAB -"
	local vReload = false
	local start_grid = 1
	--
	if type( params ) == "table" then
		--
		if type( params.label ) == "string" then
			vLabel = params.label
		end
		--
		if type( params.reload ) == "boolean" then
			vReload = params.reload
		end
		--
		--
	end
	
	print("CURR_MONSTER_ID: ", CURR_MONSTER_ID)
	start_grid = index
	
	------------------
	-- Groups
	------------------
	
	local localGroup = display.newGroup()
	
	local dragGroup = display.newGroup();

	------------------
	-- Display Objects
	------------------
	
	local background = display.newImage( "background2.png" )
	local title = display.newText( vLabel, 0, 0, native.systemFontBold, 16 )
	
	offSetX = 160
	-- local qq = display.newImage( imgPath .. "jessica_600x900.jpg" )
	-- qq.x = 0 + offSetX
	-- qq.y = 0
	-- qq.width = 200
	-- qq.height = 300
	-- local qq2 = display.newImage( imgPath .. "ironman_200x300.jpg" )
	-- qq2.x = 100 + 2*offSetX
	-- qq2.y = 0
	-- local qq3 = display.newImage( imgPath .. "padukon_200x300.jpg" )
	-- qq3.x = 160 + 3*offSetX
	-- qq3.y = 0
	-- local qq4 = display.newImage( imgPath .. "hulk_200x300.jpg" )
	-- qq4.x = 260*3
	-- qq4.y = 0
	-- local qq5 = display.newImage( imgPath .. "hulk_200x300.jpg" )
	-- qq5.x = 260*4
	-- qq5.y = 0

	-- dragGroup:insert(qq)
	-- dragGroup:insert(qq2)
	-- dragGroup:insert(qq3)
	-- dragGroup:insert(qq4)
	-- dragGroup:insert(qq5)
	dragGroup.x = 0;
	dragGroup.y = 230;
	
	--grid
	itemWidth = 200
	itemHeight = 300
	unit_w = 200
	unit_h = 300
	gridGroup = display.newGroup()
	gridGroup.y = -150
	function makeTiles(rowcnt,colcnt,unit_w,unit_h,cellpadding,leftmargin,topmargin)
		
		for i = 1, rowcnt, 1 do
			for j = 1, colcnt, 1 do
				x = (j-1)*(unit_w + cellpadding)+leftmargin
				y = topmargin + (i-1)*(unit_h + cellpadding)
				local unit = display.newRect( x, y, unit_w, unit_h )
				unit.alpha = 0.1
				gridGroup:insert(unit)

			end
		end
	end
	function putGrid(row,column,img,grid,cellpadding,leftmargin,topmargin)
		local slotGrp = display.newGroup()
		slotGrp.x = (column-1)*(unit_w + cellpadding) + offSetX
		slotGrp.y = 150

		local  item = display.newImageRect( img, itemWidth, itemHeight )
		--item.x = (column-1)*(unit_w + cellpadding) + offSetX
		--item.y = 150
		slotGrp:insert(item)

		--sphere
		local magicSphere = display.newCircle(0, 0, 86)
		magicSphere.x = 0
		magicSphere.y = 170
		--magicSphere.width = 210
		--magicSphere.height = 50
		magicSphere.yScale = 0.2
		magicSphere.alpha = 0.7
		magicSphere.strokeWidth = 30
		magicSphere:setStrokeColor(128,0,0)
		magicSphere:setFillColor(128,128,0)
		slotGrp:insert(magicSphere)

		grid:insert(slotGrp)
	end
	function putGridZero(row,column,img,grid,cellpadding,leftmargin,topmargin)
		local item
		
		local slotGrp = display.newGroup()
		slotGrp.x = (column-1)*(unit_w + cellpadding) + offSetX
		slotGrp.y = 150

		local item_touched = function ( event )
			if ( event.phase == "began" ) then
				print ("mula sentuh gergasi")
			elseif ( event.phase == "moved" ) then
				--item.alpha = 0.0
				print ("gergasi moved")
			elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
				--item.alpha = 0.5
				print ("abisss")
			end

			print("monster touched")
			--return true
			
		end
		item = display.newImageRect( img, itemWidth, itemHeight )
		--item.x = (column-1)*(unit_w + cellpadding) + offSetX
		--item.y = 150
		item.alpha = 0.1
		item:addEventListener( "touch" , item_touched )
		slotGrp:insert(item)

		--sphere
		local magicSphere = display.newCircle(0, 0, 86)
		magicSphere.x = 0
		magicSphere.y = 170
		--magicSphere.width = 210
		--magicSphere.height = 50
		magicSphere.yScale = 0.2
		magicSphere.alpha = 0.7
		magicSphere.strokeWidth = 30
		magicSphere:setStrokeColor(128,0,0)
		magicSphere:setFillColor(128,128,0)
		slotGrp:insert(magicSphere)

		local qq_monster = display.newImage( imgPath .. "summon_48.png" )
		--qq_monster.x = display.contentWidth/2
		qq_monster.y = 0
		qq_monster.x = 0
		qq_monster.alpha = 0.7
		slotGrp:insert(qq_monster)
				
		local moveUp
		local moveDown
		function moveUp()
				--print("moveUp()")
				transition.to( qq_monster, { time=2000, delay=0, y=-50, onComplete=moveDown} )
		end
		 
		function moveDown()
				transition.to( qq_monster, { time=1000, delay=0, y=0, onComplete=moveUp} )
		end	
		--transition.to( qq_monster, { time=2000, delay=500, y=display.contentHeight/2+50, onComplete=moveUp} )
		moveUp()
		
		local rainLight = display.newRect( -100, -160, 200, 350 )
		rainLight.alpha = 0.0001
		
		local function showRainLight()
			local myclosure = function() transition.to(rainLight, { time=800, alpha=0.5}) end
			timeShowId = timer.performWithDelay(400, myclosure, 1)	
		end
		local function hideRainLight()
			local myclosure = function() transition.to(rainLight, { time=100, alpha=0.0}) end
			timeHideId = timer.performWithDelay(10, myclosure, 1)	
		end
		slotGrp:insert(rainLight)

		grid:insert(slotGrp)
	end
	
	function putGridLocked(row,column,img,grid,cellpadding,leftmargin,topmargin, rq_level, rq_token)
		local item
		
		local slotGrp = display.newGroup()
		slotGrp.x = (column-1)*(unit_w + cellpadding) + offSetX
		slotGrp.y = 150

		local item_touched = function ( event )
			if ( event.phase == "began" ) then
				print ("mula sentuh gergasi")
			elseif ( event.phase == "moved" ) then
				--item.alpha = 0.0
				print ("locked moved")
			elseif ( event.phase == "ended" or event.phase == "cancelled" ) then
				--item.alpha = 0.5
				print ("is locked")
				
			end

			print("monster touched")
			--return true
			
		end

		--sphere
		local magicSphere = display.newCircle(0, 0, 86)
		magicSphere.x = 0
		magicSphere.y = 170
		--magicSphere.width = 210
		--magicSphere.height = 50
		magicSphere.yScale = 0.2
		magicSphere.alpha = 0.7
		magicSphere.strokeWidth = 30
		magicSphere:setStrokeColor(128,0,0)
		magicSphere:setFillColor(128,128,0)
		slotGrp:insert(magicSphere)

		local qq_monster = display.newImage( imgPath .. "locked.png" )
		--qq_monster.x = display.contentWidth/2
		qq_monster.y = 0
		qq_monster.x = 0
		qq_monster.alpha = 0.7
		slotGrp:insert(qq_monster)
		
		local lockedText= display.newText( "     Unlock\n\rRequires " .. rq_level .." LV\n    Token: " .. rq_token , 0, 0, native.systemFontBold, 16 )
		lockedText.x = 4
		lockedText.y = 50
		slotGrp:insert(lockedText)
						
		grid:insert(slotGrp)
	end
	
	function calcIndex(dist)
		-- 0, 320, 
		print (dist)
	end
	
	--makeTiles(1,5,200,300,60,60,0)
	--get monster_slot list from db
	local monsterArr = {}
	local slotNo = 1;
	local sql = "SELECT ms.*,m.img_320,m.mon_name from monster_slot ms" ..
	            " LEFT JOIN monster m ON ms.monster_id=m._id"
	--for row in db:nrows("SELECT * FROM monster_slot") do
	for row in db:nrows(sql) do
		local text = row._id.." "..row._id
		if (row.is_unlock == 1) then
				if (row.monster_id == 0) then
					monsterArr[slotNo] = 0
					putGridZero(1,slotNo,imgPath .. "goku_200x300.jpg",gridGroup,60,60,5)
				else
					monsterArr[slotNo] = row._id
					putGrid(1,slotNo,imgPath .. row.img_320,gridGroup,60,60,5)
				end
		else
				monsterArr[slotNo] = -1
				putGridLocked(1,slotNo,imgPath .. "locked.png",gridGroup,60,60,5, row.unlock_rq_token, row.unlock_rq_lvl)
		end
		slotNo = slotNo + 1
	end

--	putGrid(1,1,imgPath .. "therockk_200x300.jpg",gridGroup,60,60,5)
--	putGrid(1,2,imgPath .. "hulk_200x300.jpg",gridGroup,60,60,5)
--	putGridZero(1,2,imgPath .. "goku_200x300.jpg",gridGroup,60,60,5)
	--putGrid(1,3,imgPath .. "afro_samurai.png",gridGroup,60,60,5)
	--putGrid(1,3,imgPath .. "padukon_200x300.jpg",gridGroup,60,60,5)
--	putGrid(1,4,imgPath .. "ironman_200x300.jpg",gridGroup,60,60,5)
	--putGrid(1,5,imgPath .. "jessica_200x300.jpg",gridGroup,60,60,5)
--	putGrid(1,6,imgPath .. "chopra_200x300.jpg",gridGroup,60,60,5)
	
		for i=1,5,1 do
			maxrow=1
			maxcol=5
			r = math.ceil(i/maxrow) --what row?
			c = i - (r-1)*maxcol    --what column?
			--putGrid(r,c,myImages[i],gridGroup,60,60,5)
			print("row=",r ,"col=", c)
		end
	dragGroup:insert(gridGroup)
	
	function scrollGrid(i)
		CURR_MONSTER_ID = monsterArr[i]
		CURR_SLOT_NO = i
		preference.save{CURR_MONSTER_ID=monsterArr[i]}
		preference.save{CURR_SLOT_NO=i}
		i = i-1
		--dragGroup.x = -(i*(260))  -- i*(itemWidth + cellpadding)
		tween = transition.to( dragGroup, {time=400, x=-(i*(260)) } )
		--transition.to(rainLight, { time=10, alpha=0})
		--transition.to(rainLight, { time=4000, alpha=1})
		--tween = transition.to( dragGroup, {time=400, x=-(i*(260)), transition=easing.outExpo } )
		--tween = transition.to( items[itemNum+1], {time=400, x=screenW*.5, transition=easing.outExpo } )
		--rainLight.alpha = 0.5
	end
	
	function scrollGridFast(i)
		CURR_MONSTER_ID = monsterArr[i]
		preference.save{CURR_MONSTER_ID=monsterArr[i]}
		preference.save{CURR_SLOT_NO=i}
		i = i-1
		dragGroup.x = -(i*(260))  -- i*(itemWidth + cellpadding)
		--tween = transition.to( dragGroup, {time=400, x=-(i*(260)) } )
	end
	
	--popup grid coin
	itemWidth = 50
	itemHeight = 50
	unit_w = 50
	unit_h = 50
	gridGroupCoin = display.newGroup()
	function makeTilesCoin(rowcnt,colcnt,unit_w,unit_h,cellpadding,leftmargin,topmargin)
		--gridbg
		local 	gridbg = display.newRect( 0, 0, colcnt*(unit_w+cellpadding)+leftmargin, rowcnt*(unit_h+cellpadding)+topmargin )
				gridbg:setFillColor(140, 140, 140)
				gridbg:setStrokeColor(180, 180, 180)
				gridGroupCoin:insert(gridbg)
		
		for i = 1, rowcnt, 1 do
			for j = 1, colcnt, 1 do
				x = (j-1)*(unit_w + cellpadding)+leftmargin
				y = topmargin + (i-1)*(unit_h + cellpadding)
				local unit = display.newRect( x, y, unit_w, unit_h )
				gridGroupCoin:insert(unit)

			end
		end
	end
	local function bb(monster_id)
		local monDetailGrp = display.newGroup()
		local bdr2 = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
		bdr2:setReferencePoint(display.BottomLeftReferencePoint) 
		bdr2.strokeWidth = 1
		bdr2:setFillColor(255, 100, 100)
		bdr2:setStrokeColor(0, 222, 222)
		bdr2.alpha = 0.1
		
		local fncProtection2 = function( event )
			return true
		end	
		bdr2:addEventListener( "tap", fncProtection2 )
		localGroup:insert(bdr2)
		
		local w, h = display.contentWidth, display.contentHeight
		local background = display.newImage( "background3.png" )
		background.xScale = 1
		background.yScale = 0.8
		background.alpha = 1
		--close button
		local closeBtn = display.newImage("images/cross_32.png") 
		closeBtn.x = 307
		closeBtn.y = 50
		function closeBtn:tap(e)  
			--bdr.isVisible = false;
			print("pangkah popup monster!!!")
			if monDetailGrp.numChildren > 0 then
					for i=monDetailGrp.numChildren,1,-1 do
					   monDetailGrp[i]:removeSelf()
					   monDetailGrp[i] = nil
					end
			end 
			localGroup:remove(monDetailGrp)
			monDetailGrp = nil
		end  
		closeBtn:addEventListener( "tap", closeBtn )
		--'Summon' button
		local function refreshScene()
			director:changeScene( "lab", "fade" )
		end
		local function onGoSummonEvent(event)
			print("HAHA now i really wanna summonnnnnnn")
			print("curr_slot_no : ", CURR_SLOT_NO)
			--update MONSTER_SLOT in db
			local sql = "UPDATE monster_slot SET monster_id=" .. monster_id .. " WHERE _id=".. CURR_SLOT_NO ..";"
			db:exec( sql )
			local alert = native.showAlert( "Summon", "Monster summoned successfully", { "OK" }, refreshScene )						
			

		end
		local goSummonBtn = widget.newButton{
			id = "summonBtn",
			default =  imgPath .. "btn_bg.png",
			over =  imgPath .. "btn_black.png",
			width = 152, height = 40,
			onEvent = onGoSummonEvent
		}
		goSummonBtn.x = 160
		goSummonBtn.y = 380
		local goSummonText = display.newText( "Summon", 135, 370, native.systemFontBold, 14 )
		
		--popup title
		local popupTitle = display.newText( "MONSTER COIN", 100, 50, native.systemFontBold, 20 )
		--get monster info
		local m = ""
		local sql = "SELECT * FROM monster WHERE _id=" .. monster_id
		for row in db:nrows(sql) do
			m = imgPath .. row.img_320
		end

		--add monster image
		local monImg = display.newImage(m)
		monImg.x = 160
		monImg.y = 255
		monImg.xScale = 1
		monImg.yScale = 1

		--add to grp
		monDetailGrp:insert(bdr2)
		monDetailGrp:insert(background)
		monDetailGrp:insert(monImg)
		monDetailGrp:insert(closeBtn)
		monDetailGrp:insert(popupTitle)
		monDetailGrp:insert(goSummonBtn)
		monDetailGrp:insert(goSummonText)
		--add to main grp
		
		-- for row in db:nrows("SELECT * FROM monster") do
		  -- local text = row.word_en.." "..row.word_my
		  -- local t = display.newText(text, 20, 30 * row._id, null, 16)
		  -- t:setTextColor(255,0,255)
		  -- monDetailGrp:insert(t)
		-- end
		localGroup:insert(monDetailGrp)

		--eo close button
	end
	function popMonster(mon_id)
		print("popupmonster before bb() : ")
		print("CURR_SLOT_NO: " .. CURR_SLOT_NO .. ", CLICKED_COIN_ID: " .. mon_id)
		bb(mon_id)
	end
	function putGridCoin(row,column,coin_id,img,grid,cellpadding,leftmargin,topmargin)
		local  item = display.newImageRect( img, itemWidth, itemHeight )
		item.x = (column-1)*(unit_w + cellpadding) + leftmargin+25
		item.y = topmargin + (row-1)*(unit_h + cellpadding) + 25
		--item:addEventListener("tap", popMonster)
		item:addEventListener("tap", function()  
			popMonster(coin_id)
		end)
		grid:insert(item)
	end
	local function aa()
		local bdr = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
		bdr:setReferencePoint(display.BottomLeftReferencePoint) 
		bdr.strokeWidth = 1
		bdr:setFillColor(100, 100, 100)
		bdr:setStrokeColor(0, 222, 222)
		bdr.alpha = 0.5
		
		local fncProtection = function( event )
			return true
		end	
		bdr:addEventListener( "touch", fncProtection )

		local closeBtnCoin = display.newImage("images/cross_32.png") 
		function closeBtnCoin:tap(e)  
			--bdr.isVisible = false;
			print("pangkah!!!")
			bdr:removeSelf()
			fncProtection = nil
			closeBtnCoin:removeSelf()
			--gridGroup:removeChildren(); 
			if gridGroupCoin.numChildren > 0 then
					for i=gridGroupCoin.numChildren,1,-1 do
					   gridGroupCoin[i]:removeSelf()
					   gridGroupCoin[i] = nil
					end
			end 
--			
		end  
		closeBtnCoin:addEventListener( "tap", closeBtnCoin )
		
		makeTilesCoin(4,5,50,50,10,10,5)
		localGroup:insert(bdr)
		gridGroupCoin:insert(closeBtnCoin)
		localGroup:insert(gridGroupCoin)
		gridGroupCoin.x = 5
		gridGroupCoin.y = 60
		closeBtnCoin.x = 300
		closeBtnCoin.y = -10
		for i=1,#myImages,1 do
		--for i=1,6,1 do
			maxrow=5
			maxcol=5
			r = math.ceil(i/maxrow) --what row?
			c = i - (r-1)*maxcol    --what column?
			putGridCoin(r,c,myCoins[i],myImages[i],gridGroupCoin,10,10,5)
			print("row=",r ,"col=", c)
		end
	end

	local function cc()
		local gachaGrp = display.newGroup()
		local bdr = display.newRect( 0, 0, display.contentWidth, display.contentHeight )
		bdr:setReferencePoint(display.BottomLeftReferencePoint) 
		bdr.strokeWidth = 1
		bdr:setFillColor(100, 100, 100)
		bdr:setStrokeColor(0, 222, 222)
		bdr.alpha = 0.5
		
		local fncProtection = function( event )
			return true
		end	
		bdr:addEventListener( "touch", fncProtection )

		local closeBtnCoin = display.newImage("images/cross_32.png") 
		function closeBtnCoin:tap(e)  
			--bdr.isVisible = false;
			print("pangkah!!!")
			bdr:removeSelf()
			fncProtection = nil
			closeBtnCoin:removeSelf()
			gachaGrp:removeSelf()
--			
		end
		closeBtnCoin:addEventListener( "tap", closeBtnCoin )
		
		localGroup:insert(bdr)
		gachaGrp:insert(closeBtnCoin)
		gachaGrp.x = 5
		gachaGrp.y = 60
		closeBtnCoin.x = 300
		closeBtnCoin.y = -10
		--popup title
		local popupTitle = display.newText( "GACHAMON", 100, 50, native.systemFontBold, 20 )
		--add monster image
		local monImg = display.newImage("images/ironman_200x300.jpg")
		monImg.x = 160
		monImg.y = 255
		monImg.xScale = 1
		monImg.yScale = 1
		gachaGrp:insert(monImg)

		local goSummonBtn = widget.newButton{
			id = "summonBtn",
			default =  imgPath .. "btn_bg.png",
			over =  imgPath .. "btn_black.png",
			width = 152, height = 40,
			onEvent = onGoSummonEvent
		}
		goSummonBtn.x = 160
		goSummonBtn.y = 380
		local goSummonText = display.newText( "Gachamon", 100, 370, native.systemFontBold, 14 )

		localGroup:insert(gachaGrp)
		

	end
	--popup gacha
	local function popGacha()
		cc()
	end

		
	--back button
	local backbt_touched = function ( event )
		--background:removeEventListener( "touch" , touched )
		print("touched jessica")
		director:changeScene( "field", "moveFromLeft" )
		return true
	end
	local backbt = display.newImage(imgPath .. "arrow_left_48.png");
	backbt:addEventListener( "touch" , backbt_touched )
	backbt.x = 30
	backbt.y = 200	

	--go tower button
	local gotowerbt_touched = function ( event )
		--background:removeEventListener( "touch" , touched )
		print("touched gotower button")
		director:changeScene( "tower", "overFromRight" )
		return true
	end
	local gotowerbt = display.newImage(imgPath .. "arrow_right_48.png");
	gotowerbt:addEventListener( "touch" , gotowerbt_touched )
	gotowerbt.x = 290
	gotowerbt.y = 200

	--summon button
	local function onSummonEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )
			print("I am gonna summon you ", CURR_SLOT_NO)
			print("curr_monster_id: ", CURR_MONSTER_ID)
			if (CURR_MONSTER_ID ~= 0) then
				print("summon suru koto ga dekimansenn, kara slot dehanaito")
				return true
			else
				aa()
			end
			--director:openPopUp( {p1="", p2=""}, "coinbox_popup" )
		end
		return true;
	end
	local summonBtn = widget.newButton{
		id = "summonBtn",
		default =  imgPath .. "summon_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onSummonEvent
	}
	summonBtn.x = 280
	summonBtn.y = 280

	--gacha button
	local function onGachaEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )
			popGacha()
		end
		return true;
	end
	local gachaBtn = widget.newButton{
		id = "gachaBtn",
		default =  imgPath .. "gacha_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onGachaEvent
	}
	gachaBtn.x = 280
	gachaBtn.y = 320

	--mix button
	local function onMixEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local mixBtn = widget.newButton{
		id = "mixBtn",
		default =  imgPath .. "mix_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onMixEvent
	}
	mixBtn.x = 280
	mixBtn.y = 360

	--mission (quest) button
	local function onMissionEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local missionBtn = widget.newButton{
		id = "missionBtn",
		default =  imgPath .. "missionButton.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onMissionEvent
	}
	missionBtn.x = 50
	missionBtn.y = 350
	
	--inventory button
	local function onInventoryEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
			director:changeScene( { back_scene="lab", start_grid=6 }, "inventory", "moveFromTop" )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local inventoryBtn = widget.newButton{
		id = "inventoryBtn",
		default =  imgPath .. "inventory_72.png",
		over =  imgPath .. "ball_32.png",
		width = 72, height = 72,
		onEvent = onInventoryEvent
	}
	inventoryBtn.x = 160
	inventoryBtn.y = 50

	--deck button
	local function onDeckEvent( event )
		local btn = event.target
		if event.phase == "press" then
			print( "User has began pressing the button with id: " .. btn.id )
		elseif event.phase == "moved" then
			print( "User has dragged their finger while pressing the button." )
		elseif event.phase == "release" then
			print( "User has lifted finger from button." )        
		end
		return true;
	end
	local deckBtn = widget.newButton{
		id = "deckBtn",
		default =  imgPath .. "summon_32.png",
		over =  imgPath .. "ball_32.png",
		width = 32, height = 32,
		onEvent = onDeckEvent
	}
	deckBtn.x = 280
	deckBtn.y = 70
	
	if (1 ~= 1) then
		print("xxxxxxxxxxx=", start_grid)
	end
	scrollGridFast(start_grid)

	levelBar.displayLevelBar()
	
	--start sprite
	local baseline = 300
	-- A sprite sheet with a green dude
	--local sheet2 = graphics.newImageSheet( "greenman.png", { width=128, height=128, numFrames=15 } )
	---local sheet2 = graphics.newImageSheet( "finalflyingdragon.png", { width=96, height=96, numFrames=16 } )


	-- play 15 frames every 500 ms
	---local instance2 = display.newSprite( sheet2, { name="man", start=1, count=16, time=3000 } )
	---instance2.x = display.contentWidth/2
	---instance2.y = baseline - 55
	---instance2:play()

	---instance2:addEventListener( "touch", onDeckEvent )
	--end aprite
	
--	local qq_monster = display.newImage( imgPath .. "summon_48.png" )
--	qq_monster.x = display.contentWidth/2
--	qq_monster.y = baseline
	--qqTween = transition.to( qq_monster, {time=400, y=350} )

	 
--	local moveUp
--	local moveDown
--	function moveUp()
			--print("moveUp()")
--			transition.to( qq_monster, { time=2000, delay=0, y=display.contentHeight/2-50, onComplete=moveDown} )
--	end
	 
--	function moveDown()
			transition.to( qq_monster, { time=2000, delay=0, y=display.contentHeight/2, onComplete=moveUp} )
--	end	
	--transition.to( qq_monster, { time=2000, delay=500, y=display.contentHeight/2+50, onComplete=moveUp} )
--	moveUp()


	

	-- local button = widget.newButton{
		-- label = "The Button",
		-- font = "HelveticaNeue-Bold",
		-- default =  imgPath .. "btn_bg.png",
		-- fontSize = 16
	-- }
	-- button.x = display.contentCenterX
	-- button.y = display.contentCenterY
	
	local function goCoinShop()
		print (" I am going to coin shop")
		director:openPopUp( {p1="", p2=""}, "gettoken_popup" )
	end
	


	
	--====================================================================--
	-- BUTTONS
	--====================================================================--
	
	------------------
	-- Functions
	------------------
	
	
	local bt01t = function ( event )
		if event.phase == "release" then
			director:changeScene( "field", "moveFromLeft" )
			return true
		end
	end
	--
	local bt02t = function ( event )
		if event.phase == "release" then
			director:changeScene( "tower", "overFromRight" )
			return true
		end
	end
	
	local function updateToken(cnt)
		--update token in db
		local sql = "UPDATE data SET coin_count=coin_count+" .. cnt .. " WHERE _id=1;"
		db:exec( sql )
	end
	local function unlockMonsterSlot(slot_id)
		--update slot in db
		local sql = "UPDATE monster_slot SET is_unlock=1 WHERE _id=" .. slot_id .. ";"
		db:exec( sql )
	end
	
	------------------
	-- UI Objects
	------------------
		
	
	
	------------------
	-- Listeners
	------------------
	
	local touched_old = function ( event )
		if event.phase == "ended" then
			if vReload then
				director:changeScene( { label="Scene Reloaded" }, "screen2","moveFromRight" )
			else
				director:changeScene( "screen1", "crossfade" )
			end
		end
	end
	local touched = function ( event )
		if ( event.phase == "began" ) then
			print("slides", event.phase)
            -- Subsequent touch events will target button even if they are outside the contentBounds of button
			startPos = event.x
			prevPos = event.x
			
		elseif event.phase == "ended" then
			print("bg dragged")
			dragGroup.x = dragGroup.x - 20
		end
	end
	function touchListener (self, touch) 
		local phase = touch.phase
		local startDragX,endDragX
		local xDistance = 0
		
		print("slides", phase)
		if ( phase == "began" ) then
            -- Subsequent touch events will target button even if they are outside the contentBounds of button
            display.getCurrentStage():setFocus( self )
            self.isFocus = true
			startDragX = dragGroup.x
			print("startDragX : " , startDragX)

			startPos = touch.x
			prevPos = touch.x
												
        elseif( self.isFocus ) then
        
			if ( phase == "moved" ) then
				--rainLight.alpha = 0.0
				---hideRainLight()
				local delta = touch.x - prevPos
				xDistance =  math.abs(touch.x - startPos)
				prevPos = touch.x
				
				dragGroup.x = dragGroup.x + delta
				

			elseif ( phase == "ended" or phase == "cancelled" ) then
				---rainLight.alpha = 0.5
				dragDistance = touch.x - startPos
				print("dragDistance: " .. dragDistance)
				endDragX = dragGroup.x
				print("endDragX : " , endDragX)
				if ((dragDistance ~= nil) and (dragDistance == 0)) then
					if (CURR_MONSTER_ID == 0) then
						print("empty SLOT")
					elseif (CURR_MONSTER_ID == -1) then
						local token_count = 0
						local function goUnlockSlot( event )
							if "clicked" == event.action then
								local i = event.index
								if 1 == i then
										-- Do nothing; dialog will simply dismiss
								elseif 2 == i then
										print("I M GONNA UNLOCK THIS SLOTTTT HAHAHA")
										--check token is enough?
										print("current slot: ", CURR_SLOT_NO)
										--get current token
										for row in db:nrows("SELECT * FROM data") do
											--local text = row._id.." "..row._id
											--if (row.is_unlock == 1) then
											print("coin: ", row.coin_count)
											token_count = row.coin_count
										end
										--get needed token
										for row in db:nrows("SELECT * FROM monster_slot WHERE _id="..CURR_SLOT_NO) do
											print("needed token: ", row.unlock_rq_token)
											needed_token = row.unlock_rq_token
										end
										if (token_count < needed_token) then
											print ("token not enough")
											local alert = native.showAlert( "Summon", "Token not enough. \nGo to token shop", { "OK" }, refreshScene )						
											--goCoinShop() //google play in app purchase
											--updateToken(1)
											--director:changeScene( "lab", "crossfade" )
										else
											unlockMonsterSlot(CURR_SLOT_NO)
											director:changeScene( "lab", "crossfade" )
										end
										

										
								end
							end
						end
						print("locked SLOT")
						--director:openPopUp( {p1=CURR_MONSTER_ID, p2=CURR_MONSTER_ID}, "locked_slot_popup" )
						local alert = native.showAlert( "Unlock Monster Slot", "Need 7 LVL\nNeed 3 Token", { "NO", "YES" }, goUnlockSlot )						
					else
						print("**************************")
						print("MONSTER SLOT touched: " .. CURR_SLOT_NO)
						print("**************************")
							director:openPopUp( {p1=CURR_SLOT_NO, p2=CURR_MONSTER_ID}, "monster_popup" )
							--popMonster.popup("kkk", localGroup)
						--return true
					end
				else
				
					if (xDistance < 160) then
						if (touch.x > startPos) then
							print("swipe right")
							if (index == 1) then
								scrollGrid(1)
							else
								index = index - 1
								scrollGrid(index)
							end
							
						else
							print("swipe left")
							if (index == 6) then
								scrollGrid(index)
							else
								index = index + 1
								scrollGrid(index)
							end
						end
					else
						 if (touch.x > startPos) then
							print ("swipe long right")
							if (index == 1) then
								scrollGrid(1)
							else
								--index = index + math.abs(math.round(dragDistance/320))
								index = index - 1
								scrollGrid(index)
							end
						else
							print ("swipe long left")
							if (index == 6) then
								scrollGrid(6)
							else
								--index = index + math.abs(math.round(dragDistance/320))
								index = index + 1
								scrollGrid(index)
							end
							-- scrollGrid(6)
						end
					end
				end
				
				
				--scrollGrid(6)
				

									
				if ( phase == "cancelled" ) then		
					print("moved cancelled")
				end

                -- Allow touch events to be sent normally to the objects they "hit"
                display.getCurrentStage():setFocus( nil )
                self.isFocus = false
														
			end
		end
					
		return true
		
	end
	
	--====================================================================--
	-- INITIALIZE
	--====================================================================--
	
	local initVars = function ()
		
		------------------
		-- Inserts
		------------------
		
		localGroup:insert( background )
		localGroup:insert( dragGroup )
		localGroup:insert( title )
		localGroup:insert( backbt )
		localGroup:insert( gotowerbt )
		

				
		------------------
		-- Positions
		------------------
		
		title.x = 160
		title.y = 5
		
		------------------
		-- Colors
		------------------
		
		title:setTextColor( 255,255,255 )
		
		------------------
		-- Listeners
		------------------
		
		--background:addEventListener( "touch" , touched )
		background.touch = touchListener
		background:addEventListener( "touch", background )
		
	end
	
	------------------
	-- Initiate variables
	------------------
	
	initVars()
	
	------------------
	-- MUST return a display.newGroup()
	------------------
	
	return localGroup
	
end
